package psi.services;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * 主菜单 Service
 * 
 * @author 李静波
 *
 */
public class MainMenuService extends PSIBaseService {
	public List<Record> mainMenuItems() {
		List<Record> result = new ArrayList<Record>();

		UserService us = new UserService();

		// 第一级菜单
		String sql = "";
		sql += "select id, caption, fid from t_menu_item ";
		sql += " where parent_id is null order by show_order ";

		List<Record> data1 = Db.find(sql);
		for (Record r1 : data1) {
			String id1 = r1.getStr("id");

			// 第二级菜单
			sql = "select id, caption, fid from t_menu_item ";
			sql += " where parent_id = ? order by show_order ";

			List<Record> data2 = Db.find(sql, id1);
			List<Record> m2 = new ArrayList<Record>();

			for (Record r2 : data2) {
				if (!us.hasPermission(r2.getStr("fid"))) {
					continue;
				}

				String id2 = r2.getStr("id");

				// 第三级菜单
				sql = "select id, caption, fid from t_menu_item ";
				sql += " where parent_id = ? order by show_order ";

				List<Record> data3 = Db.find(sql, id2);
				List<Record> m3 = new ArrayList<Record>();
				for (Record r3 : data3) {
					if (us.hasPermission(r3.getStr("fid"))) {
						r3.set("children", new ArrayList<Record>());

						m3.add(r3);
					}
				}

				r2.set("children", m3);

				m2.add(r2);
			}

			if (!m2.isEmpty()) {
				r1.set("children", m2);

				result.add(r1);
			}
		}

		return result;
	}

	public List<Record> recentFid() {
		UserService us = new UserService();
		String userId = us.getLoginUserId();

		String sql = "";
		sql += " select distinct f.fid, f.name ";
		sql += " from t_recent_fid r,  t_fid f, t_permission p, t_role_permission rp, t_role_user ru ";
		sql += " where r.fid = f.fid and r.user_id = ? and r.fid = p.fid ";
		sql += "   and p.id = rp.permission_id and rp.role_id = ru.role_id ";
		sql += "   and ru.user_id = ? ";
		sql += " order by r.click_count desc ";
		sql += " limit 10 ";

		return Db.find(sql, userId, userId);
	}

	public void insertRecentFid(String fid) {
		if (fid == null) {
			return;
		}

		UserService us = new UserService();
		String userId = us.getLoginUserId();
		if (userId == null) {
			return;
		}

		String sql = "select click_count from t_recent_fid where user_id = ? and fid = ? ";
		Integer clickCount = Db.queryInt(sql, userId, fid);
		if (clickCount == null) {
			sql = "insert into t_recent_fid(fid, user_id, click_count) values (?, ?,  1)";
			Db.update(sql, fid, userId);
		} else {
			clickCount++;

			sql = "  update t_recent_fid ";
			sql += " set click_count = ? ";
			sql += " where user_id = ? and fid = ? ";
			Db.update(sql, clickCount, userId, fid);
		}
	}

	public String getFIdName(String fid) {
		return Db.queryStr("select name from t_fid where fid = ?", fid);
	}
}
